<?php

namespace plugin\cms\app\bll;

use core\lib\schema\Schema;
use core\attribute\Template;
use Exception;
use Illuminate\Database\Schema\Blueprint;
use plugin\cms\app\validate\Model as ValidateModel;
use support\Db;
use Webman\Event\Event;

/**
 * 模型
 */
class Model
{
    /**
     * 获取单个模型
     *
     * @param integer $id
     * @param integer $siteid
     * @return array|null
     */
    public function find(int $id, ?int $siteid = null): array|null
    {
        $table = Db::table('cms_model')
            ->where('id', '=', $id)
            ->when($siteid != null, function ($query) use ($siteid) {
                $query->whereIn('siteid',  [$siteid, 0]);
            })
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }

    /**
     * 查询模型
     *
     * @return array
     */
    #[Template]
    public function select(array $siteid = []): array
    {
        return  Db::table('cms_model')
            ->when(count($siteid) > 0, function ($query) use ($siteid) {
                $query->whereIn('siteid', $siteid);
            })
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 根据表名查找
     *
     * @param string $name
     * @return array|null
     */
    public function findByName(string $name): array|null
    {
        $table = Db::table('cms_model')
            ->where('tablename', '=', $name)
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }



    /**
     * 添加内容模型
     *
     * @param array $data
     * 
     */
    public function add(array $data)
    {

        $ValidateModel = new ValidateModel();
        if (!$ValidateModel->check($data)) {
            throw new Exception($ValidateModel->getSimpleError());
        }
        $data['tablename'] = 'cms_' . $data['tablename'];

        try {


            if ($this->findByName($data['tablename'])) {
                throw new Exception('表已存在');
            }

            $realtablename = getDatabasePrefix() .  $data['tablename'];
            if (Schema::tableExists($realtablename)) {
                throw new Exception('表已经存在');
            }

            //创建表
            Db::schema()->create($data['tablename'], function (Blueprint $table) {
                $table->id()->autoIncrement();
                $table->integer('cid');
                $table->integer('siteid');
                $table->string('title');
                $table->string('thumb');
                $table->longText('content');
                $table->string('keyword');
                $table->string('desc');
                $table->integer('readlimitation');
                $table->integer('points')->default(0);
                $table->integer('status')->default(1);
                $table->decimal('weight')->default(0);
                $table->integer('viewscount')->default(0);
                $table->integer('interacttype')->default(1);
                $table->integer('comment')->default(0);
                $table->integer('praise')->default(0);
                $table->integer('collect')->default(0);

                $table->integer('commentcount')->default(0);
                $table->integer('praisecount')->default(0);
                $table->integer('collectcount')->default(0);

                $table->integer('uid')->default(0);
                $table->integer('contribute')->default(0);
                $table->string('createtime');
                $table->string('updatetime');
            });



            $modelid = Db::table('cms_model')
                ->insertGetId($data);

            $fields = $this->initFields($modelid);
            Db::table('cms_model_field')->insert($fields);
        } catch (Exception $ex) {
            return $ex;
        }
    }


    /**
     * 删除模型
     *
     * @param integer $modelid
     * @return void
     */
    public function delete(int $modelid, int $siteid)
    {

        $modelinfo = $this->find($modelid, $siteid);
        if (!$modelinfo) {
            throw new Exception('模型不存在');
        }

        try {
            //删除表
            Db::schema()->table($modelinfo['tablename'], function (Blueprint $table) {
                $table->drop();
            });
            //删除字段

            Db::table('cms_model_field')
                ->where('modelid', '=', $modelid)
                ->delete();

            Db::table('cms_model')->where('id', '=', $modelid)
                ->delete();

            //删除标签内容里的数据
            Db::table('cms_tag_content')->where('modelid', '=', $modelid)
                ->delete();

            //删除所有栏目
            Db::table('cms_category')->where('mid', $modelid)
                ->delete();
        } catch (Exception $ex) {
            throw $ex;
        }
    }


    /**
     * 编辑
     *
     * @param integer $id
     * @param array $data
     * @return void
     */
    public function edit(int $id, int $siteid, array $data)
    {

        $modelinfo = $this->find($id, $siteid);

        $data['tablename'] = 'cms_' . $data['tablename'];
        if ($modelinfo['tablename'] != $data['tablename']) {

            if ($this->findByName($data['tablename'])) {
                throw new Exception('表已存在');
            }

            $realtablename = getDatabasePrefix() . 'cms_' . $data['tablename'];
            if (Schema::tableExists($realtablename)) {
                throw new Exception('表已经存在');
            }


            Db::schema()->table($modelinfo['tablename'], function (Blueprint $table) use ($data) {
                $table->rename($data['tablename']);
            });
        }
        Db::table('cms_model')->where('id', '=', $id)
            ->update($data);
    }

    /**
     * 新增模型时 初始化字段
     *
     * @return array
     */
    private function initFields(int $modelid): array
    {
        $fields = [

            [
                'modelid'      => $modelid,
                'title'        => '标题',
                'name'         => 'title',
                'type'         => 'string',
                'element'      => 'input',
                'polymorphic'  => null,
                'editor'       => 0,
                'require'      => 1,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 1,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '缩略图',
                'name'         => 'thumb',
                'type'         => 'string',
                'element'      => 'singleimage',
                'polymorphic'  => null,
                'editor'       => 0,
                'require'      => 1,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 1,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '内容',
                'name'         => 'content',
                'type'         => 'text',
                'element'      => 'ueditor',
                'polymorphic'  => 1,
                'editor'       => 1,
                'require'      => 0,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 1,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '关键词',
                'name'         => 'keyword',
                'type'         => 'string',
                'element'      => 'input',
                'polymorphic'  => 0,
                'editor'       => 0,
                'require'      => 0,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 2,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '摘要',
                'name'         => 'desc',
                'type'         => 'string',
                'element'      => 'textarea',
                'polymorphic'  => 0,
                'editor'       => 0,
                'require'      => 0,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 2,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '阅读限制',
                'name'         => 'readlimitation',
                'type'         => 'integer',
                'element'      => 'usergrade',
                'polymorphic'  => 0,
                'editor'       => 0,
                'require'      => 0,
                'reg'          => '',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '',
                'allowelement' => 1,
                'group'        => 2,
                'issystem'     => 1,
            ],
            [
                'modelid'      => $modelid,
                'title'        => '所需积分',
                'name'         => 'points',
                'type'         => 'integer',
                'element'      => 'input',
                'polymorphic'  => 0,
                'editor'       => 0,
                'require'      => 0,
                'reg'          => '/^\d+$/',
                'sourcetype'   => 0,
                'sourceval'    => '',
                'default'      => '0',
                'allowelement' => 1,
                'group'        => 2,
                'issystem'     => 1,
            ]
        ];

        return $fields;
    }


    /**
     * 可以投稿的模型
     *
     * @return array
     */
    public function contributeModel(): array
    {
        return  Db::table('cms_model')
            ->leftJoin('cms_category', 'cms_category.mid', '=', 'cms_model.id')
            ->where('cms_category.contribute', '=', 1)
            ->distinct()
            ->get(['cms_model.*'])
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }
}
